const vm = new Vue({
    el: '#main',
    data: {
        show: {
            coupon: false, // 优惠券
            couponAble: true, // 优惠券可选?
            credits: false, // 积分
            creditsAble: true, // 积分可选?
            couponText: '',

        },
        data: {
            useCredits: false,
            orderId: fxj.getSearch().get('id'),
            payWay: '2',
            usedCoupon: '0',
            total: 0,
            deduction: 0,
        },
        orderDetail: {
            coupon: [],
        },
    },
    methods: {
        closePopup,
        showPopup,
        setPayWay,
        selectedCoupon,
        nowPay,
    },
});

function apiready() {
    fxj.fixStatusBar('.fxj-header');
    fxj.fixContainer('#main', 0, '.affirm-pay', 20);
    mui.init();
    listenPaySwitch();
    reqOrderDetail();
}

function listenPaySwitch() {
    document.getElementById('paySwitch').addEventListener('toggle', function (event) {
        vm.data.useCredits = event.detail.isActive;
        if (vm.data.useCredits) {
            vm.data.total -= (~~(Number(vm.orderDetail.usablepoint) / 100));
        }
        else {
            vm.data.total += (~~(Number(vm.orderDetail.usablepoint) / 100));
        }
    });
}

function closePopup() {
    vm.show.coupon = false;
    vm.show.credits = false;
}

function showPopup(type) {
    vm.show[type] = true;
}

function reqOrderDetail() {
    ajax({
        url: 'home/order/getPayOrderDetail',
        data: {
            orderId: vm.data.orderId,
        },
    }).then(
        res => {
            if (res.err === 0) {
                vm.data.total = Number(res.data.pay_price);
                vm.orderDetail = res.data;
                if (res.data.status.status === 22) {
                    handleUsedCoupon(res.data);
                }
                if (res.data.point != null) {
                    handleUsedCredits(res.data);
                }
            }
            else {
                mui.toast(res.msg);
            }
        },
    );
}

function setPayWay(type) {
    vm.data.payWay = type;
}

function selectedCoupon(coupon) {
    if (coupon === '0') {
        vm.data.usedCoupon = '0';
        vm.data.total += vm.data.deduction;
        vm.show.couponText = '';
    }
    else {
        vm.data.usedCoupon = coupon.coupon_id ? coupon.coupon_id : '0';
        vm.show.couponText = `满${coupon.condition}减${coupon.amount}元`;
        vm.data.deduction = Number(coupon.amount);
        vm.data.total -= vm.data.deduction;
    }
}

function handleUsedCoupon(data) {
    let couponObj = null;
    vm.show.couponAble = false;
    vm.data.usedCoupon = data.coupon_id ? data.coupon_id : '0';
    data.coupon.some(coupon => {
        if (coupon.ucid === data.coupon_id) {
            couponObj = coupon;
            return true;
        }
        return false;
    });
    couponObj && selectedCoupon(couponObj);
}

function handleUsedCredits(order) {
    document.getElementById('paySwitch').classList.add('mui-active');
    vm.show.creditsAble = false;
    vm.data.useCredits = true;
    vm.data.total -= (~~(Number(order.point) / 100));
    order.usablepoint = order.point;
}

async function nowPay() {
    const payHandler = {
        '1': wxPay,
        '2': zfbPay,
    };
    const config = await reqOrderId();
    payHandler[vm.data.payWay](config);
}

function reqOrderId() {
    const data = {
        type: vm.data.payWay,
        coupon: vm.data.usedCoupon === '0' ? '-1' : vm.data.usedCoupon,
        orderId: vm.data.orderId,
        point: vm.data.useCredits ? '1' : '-1',
    };
    return new Promise(resolve => {
        ajax({
            url: 'home/pay',
            data,
        }).then(
            res => {
                resolve(res.data);
            },
        );
    });
}

async function wxPay(config) {
    const wxPay = api.require('wxPay');
    wxPay.payOrder({
        apiKey: config.appid,
        orderId: config.prepayid,
        mchId: config.partnerid,
        nonceStr: config.noncestr,
        timeStamp: config.timestamp,
        package: config.package,
        sign: config.sign,
    }, function (ret, err) {
        if (ret.status) {
            paySuccess();
            goIndentPage();
        }
    });
}

async function zfbPay(config) {
    const aliPayPlus = api.require('aliPayPlus');
    aliPayPlus.payOrder({
        orderInfo: config,
    }, function (ret, err) {
        if (Number(ret.code) === 9000) {
            paySuccess();
            goIndentPage();
        }
    });
}

function goIndentPage() {
    closeToWin();
    api.execScript({
        name: 'root',
        script: 'openIndent()',
    });
}


function paySuccess() {
    api.execScript({
        name: 'root',
        frameName: 'indent',
        script: 'reqOrderList(1)'
    })
}